package com.sscw.tcp.config;


import com.alibaba.mqtt.server.ServerConsumer;
import com.alibaba.mqtt.server.config.ChannelConfig;
import com.alibaba.mqtt.server.config.ConsumerConfig;
import com.sscw.tcp.constant.MQTTTopicConstant;
import com.sscw.tcp.mqtt.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
@Configuration
@AllArgsConstructor
public class MQTTConsumerConfig {

    private final MQTTProperties mqttProperties;

    private final AppListener appListener;

    private final MachineSendSettleListener machineSendSettleListener;


    @Bean
    public ServerConsumer serverConsumer() throws IOException, TimeoutException {
        ChannelConfig channelConfig = new ChannelConfig();
        channelConfig.setDomain(mqttProperties.getDomain());
        channelConfig.setPort(mqttProperties.getPort());
        channelConfig.setInstanceId(mqttProperties.getInstanceId());
        channelConfig.setAccessKey(mqttProperties.getAccessKey());
        channelConfig.setSecretKey(mqttProperties.getSecretKey());

        ServerConsumer serverConsumer = new ServerConsumer(channelConfig, new ConsumerConfig());
        serverConsumer.start();
        log.info("ServerConsumer 服务已开启");
        // 注册APP街机消费监听
        serverConsumer.subscribeTopic(MQTTTopicConstant.APP_FIRST_TOPIC, appListener);
        // 注册街机指令消费监听
        serverConsumer.subscribeTopic(MQTTTopicConstant.MACHINE_FIRST_TOPIC, machineSendSettleListener);
        return serverConsumer;
    }

}
